import torch

def loss(y, y_pred):
    return ((y_pred - y)**2).mean()
def forward(x):
    return w * x
# 定义数据集
X = torch.tensor([1, 2, 3, 4], dtype=torch.float32)
Y = torch.tensor([2, 4, 6, 8], dtype=torch.float32)
# 初始化w、学习率、迭代次数
w = torch.tensor(0.0, dtype=torch.float32, requires_grad=True)
lr = 0.01
n_iters = 20

for epoch in range(n_iters):
    y_pred = forward(X)
    loss_value = loss(Y, y_pred)
    loss_value.backward()
    # 更新参数
    with torch.no_grad():
        w.data -= lr * w.grad
    print(f'epoch {epoch+1}: w = {w.item():.3f}, loss = {loss_value.item():8f}, dw = {w.grad:.3f}')
    w.grad.zero_()